<template>
  <div class="stock-management">
    <el-card class="shadow-md rounded-lg p-5">
      <template #header>
        <div class="card-header flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold text-gray-800">药品库存管理</h2>
          <el-button 
            type="primary" 
            @click="openStockDialog()"
            class="bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 flex items-center px-4 py-2">
            <el-icon><Plus /></el-icon>
            <span>新增库存</span>
          </el-button>
        </div>
      </template>

      <el-table 
        :data="stockList" 
        border 
        stripe
        highlight-current-row
        style="width: 100%"
        class="rounded-lg overflow-hidden mb-4">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="medicineId" label="药品ID" align="center"></el-table-column>
        <el-table-column prop="medicineName" label="药品名称" align="center"></el-table-column>
        <el-table-column prop="quantity" label="库存数量" align="center"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openStockDialog(scope.row)"
              class="bg-primary hover:bg-primary/90 text-white rounded transition-all duration-300 px-3 py-1">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteStock(scope.row)"
              class="bg-danger hover:bg-danger/90 text-white rounded transition-all duration-300 px-3 py-1">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex flex-col md:flex-row justify-between items-center mt-4 gap-4">
        <div class="text-sm text-gray-500">
          共 {{ total }} 条记录
        </div>
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          class="pagination w-full md:w-auto"
        ></el-pagination>
      </div>
    </el-card>

<!-- 库存编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑库存' : '新增库存'" width="50%">
      <el-form :model="stockForm" label-width="100px">
        <el-form-item label="药品">
          <el-select v-model="stockForm.medicineId" placeholder="请选择药品">
            <el-option
              v-for="item in medicineOptions"
              :key="item.id"
              :label="item.medicineName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="库存数量">
          <el-input-number v-model="stockForm.quantity" :min="0"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStock">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { listStock, getStock, addStock, updateStock, delStock } from '@/api/stock'
import { listMedicine } from '@/api/medicine'

// 引用表单进行验证
const formRef = ref(null)

// 库存列表
const stockList = ref([])

// 药品选项
const medicineOptions = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 库存表单
const stockForm = reactive({
  id: null,
  medicineId: null,
  quantity: 0,
})

// 获取库存列表
const getStockList = async (params = {}) => {
  try {
    const res = await listStock({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...params
    })

    // 获取药品列表
    const medicineRes = await listMedicine()
    const medicineMap = {}
    medicineRes.data.forEach((medicine) => {
      medicineMap[medicine.id] = medicine
    })

    // 合并药品信息
    stockList.value = res.data.map((stock) => {
      const medicine = medicineMap[stock.medicineId] || {}
      return {
        ...stock,
        medicineName: medicine.medicineName || '未知药品',
      }
    })

    total.value = res.total || 0
  } catch (error) {
    console.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  }
}

// 获取药品选项
const getMedicineOptions = async () => {
  try {
    const res = await listMedicine()
    medicineOptions.value = res.data || []
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 打开库存对话框
const openStockDialog = (stock) => {
  if (stock) {
    // 编辑模式
    isEdit.value = true
    Object.assign(stockForm, stock)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(stockForm, {
      id: null,
      medicineId: null,
      quantity: 0,
    })
  }

  dialogVisible.value = true
  
  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 验证并保存库存
const validateAndSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      saveStock()
    } else {
      return false
    }
  })
}

// 保存库存
const saveStock = async () => {
  try {
    if (!stockForm.medicineId) {
      ElMessage.warning('请选择药品')
      return
    }

    if (isEdit.value) {
      // 编辑库存
      await updateStock(stockForm)
      ElMessage.success('库存更新成功')
    } else {
      // 新增库存
      await addStock(stockForm)
      ElMessage.success('库存添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新库存列表
    getStockList()
  } catch (error) {
    console.error('保存库存失败', error)
    ElMessage.error(error.message || '保存库存失败')
  }
}

// 删除库存
const deleteStock = (stock) => {
  ElMessageBox.confirm(`确定要删除药品 ${stock.medicineName} 的库存记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delStock(stock.id)
        ElMessage.success('库存删除成功')
        getStockList()
      } catch (error) {
        console.error('删除库存失败', error)
        ElMessage.error(error.message || '删除库存失败')
      }
    })
    .catch(() => {})
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page
  getStockList()
}

// 每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getStockList()
}

// 初始化
onMounted(() => {
  getStockList()
  getMedicineOptions()
})
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary: #409eff;
  --success: #67c23a;
  --warning: #e6a23c;
  --danger: #f56c6c;
  --info: #909399;
  --bg-light: #f5f7fa;
  --text-primary: #303133;
  --text-secondary: #606266;
  --text-placeholder: #909399;
  --border-color: #dcdfe6;
  --border-radius: 8px;
  --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 工具类 */
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.items-center { align-items: center; }
.rounded-lg { border-radius: var(--border-radius); }
.shadow-md { box-shadow: var(--box-shadow); }
.mb-4 { margin-bottom: 16px; }
.mb-5 { margin-bottom: 20px; }
.p-4 { padding: 16px; }
.p-5 { padding: 20px; }
.gap-4 { gap: 16px; }
.text-xl { font-size: 20px; }
.font-bold { font-weight: 600; }
.text-gray-800 { color: var(--text-primary); }
.text-gray-500 { color: var(--text-secondary); }
.bg-gray-50 { background-color: var(--bg-light); }
.w-64 { width: 256px; }

/* 卡片样式 */
.shadow-md {
  box-shadow: var(--box-shadow);
}

/* 表格样式 */
.rounded-lg {
  border-radius: var(--border-radius);
}

/* 分页样式 */
.pagination {
  margin-top: 0;
}

/* 对话框样式 */
.dialog-shadow {
  box-shadow: var(--box-shadow);
  border-radius: var(--border-radius);
  z-index: 2000;
}

/* 按钮过渡效果 */
button {
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stock-management {
    padding: 10px;
  }
  
  .el-card {
    padding: 15px;
  }
  
  .el-table-column {
    min-width: auto !important;
  }
  
  .el-pagination {
    white-space: normal;
  }
  
  .dialog-shadow {
    width: 90%;
  }
  
  .search-area .el-form-item {
    margin-bottom: 10px;
  }
}
</style>